import { MessageBox } from 'element-ui'

/**
 * 确认提示框装饰器
 * @param {*} options 配置项
 * @param {*} cancelFn 取消回调函数
 */
export function confirmDecorator(options, cancelFn = () => {}) {
  return function(target, name, descriptor) {
    const originFn = descriptor.value
    descriptor.value = async function(...args) {
      let op = {
        title: '提示',
        center: false,
        customClass: '__message-confirm-box',
        message: '提示消息'
      }
      op = Object.assign(op, options)
      let message = op.message
      if (op.subMessage) {
        let subMessage = op.subMessage
        const index = subMessage.indexOf('#p')
        const dotIndex = subMessage.indexOf('.')
        // 处理参数表达式
        if (index !== -1) {
          const argIndex = parseInt(subMessage.substring(2, dotIndex))
          if (dotIndex > 2) {
            const prop = subMessage.substring(dotIndex + 1, subMessage.length)
            subMessage = _getValue(args[argIndex], prop)
          } else {
            subMessage = args[argIndex]
          }
        }
        message = `<p style="font-size: 18px">${message}</p><p style="margin-top: 8px">${subMessage}</p>`
        op.dangerouslyUseHTMLString = true
        op.message = message
      }
      MessageBox.confirm(message, op.title, op).then(() => {
        originFn.apply(this, args)
      }).catch((error) => {
        cancelFn && cancelFn(error)
      })
    }
  }
}

/**
 * 提示框装饰器
 * @param {*} options 配置项
 */
export function alertDecorator(options) {
  return function(target, name, descriptor) {
    const originFn = descriptor.value
    descriptor.value = async function(...args) {
      let op = {
        title: '提示',
        center: false,
        customClass: '__message-confirm-box',
        message: '提示消息'
      }
      op = Object.assign(op, options)
      MessageBox.alert(op.message, op.title, op).then(() => {
        originFn.apply(this, args)
      })
    }
  }
}

function _getValue(data, prop) {
  if (!prop) return
  if (prop.indexOf('.') !== -1) {
    const paths = prop.split('.')
    let current = data
    let result = null
    for (let i = 0, j = paths.length; i < j; i++) {
      const path = paths[i]
      if (!current) break
      if (i === j - 1) {
        result = current[path]
        break
      }
      current = current[path]
    }
    return result
  } else {
    return data[prop]
  }
}
